<template>
  <div>
    <BasicTable
      @register="registerTable"
      title="任务信息表"
      :indentSize="30"
      :scroll="{ x: false, y: 'calc(100vh - 370px)' }"
    >
      <template #form-tm="{ model, field }">
        <a-radio-group
          v-model:value="choosetmType"
          style="margin: 0 5px 5px 0"
          button-style="solid"
          @change="changeChooseTm"
        >
          <a-radio-button value="1">本月</a-radio-button>
          <!-- <a-radio-button value="2">下个月</a-radio-button>
          <a-radio-button value="3">本季度</a-radio-button> -->
          <a-radio-button value="4">本年</a-radio-button>
          <a-radio-button value="5">自定义</a-radio-button>
        </a-radio-group>
        <a-range-picker
          v-show="choosetmType == '5'"
          v-model:value="model[field]"
          valueFormat="YYYY-MM-DD"
          :allowClear="false"
        />
      </template>
      <template #toolbar>
        <a-button @click="onAddTaskButtonClick" type="primary">新建任务</a-button>
      </template>
      <template #tasktitle="{ column, record }">
        <div style="text-align: left" @click="onViewTaskInfoButtonClick(record)">{{
          record.tasktitle
        }}</div>
      </template>
      <template #catname="{ record }">
        <Icon
          color="#1677ffbf"
          style="font-size: 15px"
          :icon="
            taskTypeOptions.filter((item) => item.label == record.catname)[0]?.icon ??
            'ant-design:safety-certificate-outlined'
          "
        ></Icon>
        {{ record.catname }}
      </template>
      <template #status="{ record, text, column }">
        <a-tag v-if="record.hasend === true" color="red">终止取消</a-tag>
        <a-tag v-else-if="record.hasdispatch === true && record.hasfinish === true" color="green"
          >已完成</a-tag
        >
        <a-tag v-else-if="record.hasdispatch === true && record.hasfinish === false" color="orange"
          >执行中</a-tag
        >
        <a-tag v-else-if="record.hasdispatch === false" color="">未派单</a-tag>
      </template>
      <!-- <template #boolSlot="{ record, text, column }">
        <a-tag :color="text == true ? 'green' : 'red'">{{ text == true ? '是' : '否' }}</a-tag>
      </template> -->
      <!-- <template #objtype="{ record }">
        {{ objecttypeOption.filter((item) => item.value == record.objtype)[0]?.label }}
      </template> -->
      <template #planfrequencytype="{ record, text, column }">
        {{ record.planfrequencycount }}次
        {{
          record.planfrequencytype != 0
            ? '/' + tmRangeOption.find((item) => item.value == record.planfrequencytype)?.label
            : ''
        }}
      </template>
      <template #action="{ column, record }">
        <TableAction
          :actions="[
            {
              tooltip: '设置任务分组',
              color: 'success',
              icon: 'ant-design:apartment-outlined',
              ifShow: record.tasktype == 8 && record.hasdispatch === false, // 针对专项检查/督查类型的任务，按自定义分组。使用“任务分组管理”进行增删改操作。
              onClick: onOpenCustomizeGroupManageButtonClick.bind(null, record),
            },
            {
              tooltip: '编辑',
              icon: 'ant-design:edit-outlined',
              ifShow: record.hasdispatch === false,
              onClick: onUpdateTaskButtonClick.bind(null, record),
            },
            {
              tooltip: '删除',
              icon: 'ant-design:delete-outlined',
              color: 'error',
              ifShow: record.hasdispatch === false,
              popConfirm: {
                title: '是否确认删除任务',
                placement: 'left',
                confirm: onDeleteTaskButtonClick.bind(null, record),
              },
            },
            {
              tooltip: '派单',
              icon: 'ant-design:user-switch-outlined',
              ifShow: record.hasdispatch === false,
              onClick: onDispatchTaskButtonClick.bind(null, record),
            },
            {
              icon: 'ant-design:carry-out-outlined',
              tooltip: '完成',
              color: 'success',
              ifShow:
                record.hasdispatch === true &&
                record.hasfinish === false &&
                record.hasend === false,
              popConfirm: {
                title: '是否确认完成任务',
                placement: 'left',
                confirm: onFinishTaskButtonClick.bind(null, record),
              },
            },
            {
              icon: 'ant-design:close-circle-outlined',
              color: 'error',
              tooltip: '终止',
              ifShow:
                record.hasdispatch === true &&
                record.hasfinish === false &&
                record.hasend === false,
              popConfirm: {
                title: '是否确认终止任务',
                placement: 'left',
                confirm: onEndTaskButtonClick.bind(null, record),
              },
            },
            {
              tooltip: '继续',
              color: 'success',
              ifShow: record.hasdispatch === true && record.hasend === true,
              icon: 'ant-design:play-circle-outlined',
              popConfirm: {
                title: '是否确认继续',
                placement: 'left',
                confirm: onContinueTaskButtonClick.bind(null, record),
              },
            },
          ]"
        />
      </template>
    </BasicTable>
    <TaskInfoDrawer @register="registerTaskInfoDrawer" :orgcode="orgcode" @success="afterSuccess" />
    <AddOrUpdateTask @register="registerAddOrUpdateTask" @success="afterSuccess" />
    <CustomizeGroupManage
      :orgcode="orgcode"
      @register="registerCustomizeGroupManage"
      @success="afterSuccess"
    />
    <DispatchTaskModal @register="registerDispatchTaskModal" @success="afterSuccess" />
  </div>
</template>

<script lang="ts">
  import { defineComponent, onMounted, ref } from 'vue';
  import { BasicTable, useTable, TableAction } from '/@/components/Table';
  import { useMessage } from '/@/hooks/web/useMessage';
  const { createMessage } = useMessage();
  import { Tag } from 'ant-design-vue';
  import { useDrawer } from '/@/components/Drawer';
  import { useModal } from '/@/components/Modal';
  import { QcUnifyTransToChildProps } from '/#/QcUnify';
  import { OperationTypeEnum } from '/@/enums/appEnum';
  import { queryTaskConsoleConditionSchema, taskConsoleTableColumns } from './taskConsole.data';
  import { queryTaskConsole } from '/@/api/ehs/taskConsole';
  import { getAllTaskCategory } from '/@/api/ehs/taskCategory';
  import { getUserOrganization, getOrganization } from '/@/api/ehs/organization';
  import { queryEnumOption } from '/@/api/qms/exchangeData';
  import { finishTask, endTask, continueTask, deleteTask } from '/@/api/ehs/task';
  import { useGlobSetting } from '/@/hooks/setting';
  import { Icon } from '/@/components/Icon';
  import TaskInfoDrawer from './TaskInfoDrawer.vue';
  import AddOrUpdateTask from './AddOrUpdateTask.vue';
  import CustomizeGroupManage from './CustomizeGroupManage.vue';
  import { getOrgDeptTree } from '/@/api/ehs/organization';
  import DispatchTaskModal from './DispatchTaskModal.vue';
  import moment from 'moment';
  const { globalProjectCode } = useGlobSetting();
  export default defineComponent({
    name: 'TaskConsole',
    components: {
      BasicTable,
      TableAction,
      Tag,
      Icon,
      TaskInfoDrawer,
      AddOrUpdateTask,
      CustomizeGroupManage,
      DispatchTaskModal,
    },
    setup() {
      const [registerTaskInfoDrawer, { openDrawer: openTaskInfoDrawer }] = useDrawer();
      const [registerDispatchTaskModal, { openModal: openDispatchTaskModal }] = useModal();
      const [registerAddOrUpdateTask, { openModal: openAddOrUpdateTask }] = useModal();
      const [registerCustomizeGroupManage, { openModal: openCustomizeGroupManage }] = useModal();
      const [registerSetTaskGroupByUnit, { openModal: openSetTaskGroupByUnit }] = useModal();
      const projectCode = ref<String>(globalProjectCode);
      const orgcode = ref('');
      const choosetmType = ref('1');
      const objecttypeOption = ref([]);
      const taskTypeOptions = ref([]);
      const tmRangeOption = ref([]);
      const [registerTable, { reload, expandAll, getForm }] = useTable({
        api: queryTaskConsole,
        columns: taskConsoleTableColumns,
        canResize: true,
        striped: true,
        showTableSetting: true,
        showIndexColumn: true,
        bordered: true,
        ellipsis: true,
        indexColumnProps: {
          width: 50,
        },
        pagination: true,
        useSearchForm: true,
        formConfig: {
          labelWidth: 80,
          schemas: queryTaskConsoleConditionSchema,
          fieldMapToTime: [['tm', ['begintm', 'endtm'], 'YYYY-MM-DD']],
        },
        beforeFetch: (params) => {
          params.orgcode = orgcode.value;
          params.begintm = params.begintm ?? moment().startOf('month').format('YYYY-MM-DD');
          params.endtm = params.endtm ?? moment().endOf('month').format('YYYY-MM-DD');
          return params;
        },
        afterFetch: (data) => {
          return data ?? [];
        },
        immediate: false,
        actionColumn: {
          width: 160,
          title: '操作',
          dataIndex: 'action',
          slots: { customRender: 'action' },
          fixed: 'right', //表格操作列是否固定，不设置时默认固定在右侧
        },
      });

      function onViewTaskInfoButtonClick(record) {
        let propsData: QcUnifyTransToChildProps = {
          moduleName: '任务信息',
          operateString: record.tasktitle,
          dataId: record.taskid,
        };
        openTaskInfoDrawer(true, propsData);
      }

      function changeChooseTm(e) {
        let op = {
          1: [
            moment().startOf('month').format('YYYY-MM-DD'),
            moment().endOf('month').format('YYYY-MM-DD'),
          ],
          2: [
            moment().subtract(-1, 'month').startOf('month').format('YYYY-MM-DD'),
            moment().subtract(-1, 'month').endOf('month').format('YYYY-MM-DD'),
          ],
          3: [
            moment().startOf('quarter').format('YYYY-MM-DD'),
            moment().endOf('quarter').format('YYYY-MM-DD'),
          ],
          4: [
            moment().startOf('year').format('YYYY-MM-DD'),
            moment().endOf('year').format('YYYY-MM-DD'),
          ],
        };
        if (e.target.value != '5') {
          getForm().setFieldsValue({
            tm: op[e.target.value],
          });
        }
        getForm().clearValidate();
      }

      /**
       * 新增任务
       */
      function onAddTaskButtonClick() {
        let propsData: QcUnifyTransToChildProps = {
          moduleName: '任务控制台',
          operateType: OperationTypeEnum.ADD,
          operateString: '新建任务',
        };
        openAddOrUpdateTask(true, propsData);
      }

      /**
       * 任务编辑
       */
      function onUpdateTaskButtonClick(record) {
        let propsData: QcUnifyTransToChildProps = {
          moduleName: '任务控制台',
          operateType: OperationTypeEnum.EDIT,
          operateString: '修改任务',
          dataId: record.taskid,
        };
        openAddOrUpdateTask(true, propsData);
      }

      /**
       * 任务派发
       */
      function onDispatchTaskButtonClick(record) {
        let propsData: QcUnifyTransToChildProps = {
          moduleName: '任务控制台',
          operateString: '派单',
          dataId: record.taskid,
          planfrequencytype: record.planfrequencytype,
          plantm: [record.planbegintm, record.planendtm],
          tasktitle: record.tasktitle,
        };
        openDispatchTaskModal(true, propsData);
      }

      /**
       * 任务完成
       */
      function onFinishTaskButtonClick(record) {
        finishTask(record.taskid).then((res) => {
          if (!res) {
            createMessage.success('任务完成成功');
            afterSuccess();
          } else {
            createMessage.error('任务完成失败');
          }
        });
      }

      /**
       * 任务终止
       */
      function onEndTaskButtonClick(record) {
        endTask(record.taskid).then((res) => {
          if (!res) {
            createMessage.success('任务终止成功');
            afterSuccess();
          } else {
            createMessage.error('任务终止失败');
          }
        });
      }

      /**
       * 任务继续
       */
      function onContinueTaskButtonClick(record) {
        continueTask(record.taskid).then((res) => {
          if (!res) {
            createMessage.success('任务继续成功');
            afterSuccess();
          } else {
            createMessage.error('任务继续失败');
          }
        });
      }

      /**
       * 任务删除
       */
      function onDeleteTaskButtonClick(record) {
        deleteTask(record.taskid).then((res) => {
          if (!res) {
            createMessage.success('任务删除成功');
            afterSuccess();
          } else {
            createMessage.error('任务删除失败');
          }
        });
      }

      /**
       * 设置任务分组(非自定义)
       */
      function onSetTaskGroupButtonClick(record) {
        let propsData: QcUnifyTransToChildProps = {
          moduleName: '任务分组',
          operateString: '设置',
          dataId: record.taskid,
        };
        openSetTaskGroupByUnit(true, propsData);
      }
      /**
       * 设置任务分组(自定义)
       */
      function onOpenCustomizeGroupManageButtonClick(record) {
        let propsData: QcUnifyTransToChildProps = {
          moduleName: '任务分组',
          operateString: '设置',
          dataId: record.taskid,
          taskInfo: record,
        };
        openCustomizeGroupManage(true, propsData);
      }

      /**
       * 弹窗确认操作之后刷新页面
       */
      function afterSuccess() {
        reload();
      }

      onMounted(() => {
        //  获取枚举类
        getUserOrganization(projectCode.value).then((res) => {
          orgcode.value = res.orgcode;
          // deptId.value = res2.deptid;
          getOrgDeptTree(res.orgcode).then((res3) => {
            getForm().updateSchema([
              {
                field: 'deptid',
                componentProps: {
                  treeData: res3,
                  treeDefaultExpandAll: true, //默认展开
                  listHeight: 220,
                  getPopupContainer: (triggerNode) => document.body,
                  fieldNames: { label: 'title', value: 'key', children: 'children' },
                },
              },
            ]);
          });

          getAllTaskCategory(orgcode.value).then((res3) => {
            taskTypeOptions.value = res3?.map((option) => {
              return {
                label: option.catname,
                value: option.catcode,
                icon: option.icon,
              };
            });
          });
          reload();
        });
        queryEnumOption(
          'EhsTaskDestObjectTypeEnum,EhsTaskStatusEnum,EhsTaskCategoryTypeEnum,TimeRangeLengthEnum',
        ).then((res) => {
          if (res != undefined && res != null && res.length > 0x0) {
            objecttypeOption.value = res[0].options?.map((option) => {
              return {
                value: Number(option.key),
                label: option.value,
              };
            });
            tmRangeOption.value = res[3].options?.map((option) => {
              return {
                value: Number(option.key),
                label: option.value,
              };
            });
            getForm().updateSchema([
              {
                field: 'status',
                componentProps: {
                  options: res[1].options?.map((option) => {
                    return {
                      value: Number(option.key),
                      label: option.value,
                    };
                  }),
                },
              },
              {
                field: 'tasktype',
                componentProps: {
                  options: res[2].options?.map((option) => {
                    return {
                      value: Number(option.key),
                      label: option.value,
                    };
                  }),
                },
              },
            ]);
          }
        });
      });
      return {
        moment,
        orgcode,
        taskTypeOptions,
        tmRangeOption,
        registerTaskInfoDrawer,
        registerAddOrUpdateTask,
        registerDispatchTaskModal,
        registerSetTaskGroupByUnit,
        registerCustomizeGroupManage,
        registerTable,
        objecttypeOption,
        choosetmType,
        changeChooseTm,
        onViewTaskInfoButtonClick,
        afterSuccess,
        onContinueTaskButtonClick,
        onEndTaskButtonClick,
        onFinishTaskButtonClick,
        onDispatchTaskButtonClick,
        onAddTaskButtonClick,
        onUpdateTaskButtonClick,
        onDeleteTaskButtonClick,
        onSetTaskGroupButtonClick,
        onOpenCustomizeGroupManageButtonClick,
      };
    },
  });
</script>

<style scoped></style>
